#include  <msp430x14x.h>
#include <flash.h>

char *Flash_ptr;                          // Flash pointer

void initializeFlash(int isFromFlash) {
  WDTCTL = WDTPW + WDTHOLD;                 // Stop watchdog timer
  FCTL2 = FWKEY + FSSEL0 + FN0;             // MCLK/2 for Flash Timing Generator
  
  if (isFromFlash){
	loadFromFlash();
  }else{
	_DINT();                                  // Diable Interrupts 
	while(FCTL3 & BUSY);                      // Check Flash BUSY bit
	FCTL1 = FWKEY + ERASE;                    // Set Erase bit or MERASE
	Flash_ptr = (char *) (0x1000);            // Initialize Flash pointer
	Flash_ptr = 0;                            // Dummy write to erase Flash segment
	_EINT();                                  // Enable Interrupts
  }//end if
}//end initializeFlash

/**
 *  This function loads all the values from a segment into the registers
 *
 */
void loadFromFlash(void){



}//end loadFromFlash

/**
 * This function writes to flash
 *
 */
void writeToFlash (char address, char value) {  
  unsigned int i;							// Loop counter
  
  while(FCTL3 & BUSY);                      // Check Flash BUSY bit
  
  _DINT();                                  // Diable Interrupts   
    
  Flash_ptr = (char *)0x1000+address;				// Adding the offset  
  
  FCTL3 = FWKEY;                            // Clear Lock bit

  FCTL1 = FWKEY + WRT;                      // Set WRT bit for write operation

  //*Flash_ptr++ = value;                   	// Write value to flash - for continuous write
  *Flash_ptr = value; 						// Write value to flash
  
  FCTL1 = FWKEY;                            // Clear WRT bit
  FCTL3 = FWKEY + LOCK;                     // Set LOCK bit
  
  _EINT();                                  // Enable Interrupts
}//end


/**
 * This function reads from flash
 *
 */
char readFromFlash (char address) {  
  unsigned int i;							// Loop counter
  char value;
  
  while(FCTL3 & BUSY);                      // Check Flash BUSY bit
  
  _DINT();                                  // Diable Interrupts   
  
  Flash_ptr = (char *)0x1000+address;    			// Initialize Flash pointer
  
  FCTL3 = FWKEY;                            // Clear Lock bit
  *Flash_ptr = 0;                           // Dummy write to erase Flash segment

  FCTL1 = FWKEY + WRT;                      // Set WRT bit for write operation

  value = *Flash_ptr;                   	// Write value to flash

  FCTL1 = FWKEY;                            // Clear WRT bit
  FCTL3 = FWKEY + LOCK;                     // Set LOCK bit
  
  _EINT();                                  // Enable Interrupts
  
  return value;
}//end

